<template>
  <div class="container">
    <el-card>
      <div>
        <el-button type="primary" @click="handleExport">导入设备</el-button>
      </div>
      <div style="display: flex;flex-direction: column;gap: 15px;font-size: 14px;margin-top: 20px;cursor: pointer;">
        <div v-for="(item, index) in departmentData" :key="item.id" @click="handleChange(item.id, item.departmentCode)"
          :class="{ showcChecked: checkedkeys == item.id }" style="padding: 5px 10px;border-radius: 5px;">
          {{ item.name }}
        </div>
      </div>
    </el-card>
    <el-card style="flex: 1;" class="table-container">
      <div style="margin: 0 10px 20px 10px">
        <el-form :inline="true" :model="searchForm" class="demo-form-inline">
          <el-form-item label="盘查月份" prop="assetTag">
            <el-col :span="22">
              <el-date-picker v-model="searchForm.createdTime" type="month" placeholder="选择月">
              </el-date-picker>
            </el-col>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleExportOut">导出</el-button>
          </el-form-item>
          <!-- <el-form-item>
            <el-button type="primary" @click="handleAdd">新增</el-button>
          </el-form-item> -->
          <!-- <el-form-item>
            <el-button :loading="exportLoading" type="success" plain @click="handleExportExcel">Excel导出</el-button>
          </el-form-item> -->
        </el-form>
      </div>
      <el-table :data="tableData.list" :header-row-class-name="'table-head-th'" fit v-loading="queryLoading"
        highlight-current-row>

        <el-table-column align="center" key="assetTag" show-overflow-tooltip prop="assetTag" label="资产标签号"
          width="130" />
        <el-table-column align="center" key="equipmentName" show-overflow-tooltip prop="equipmentName" label="设备名字" />
        <el-table-column align="center" key="specificLocation" show-overflow-tooltip prop="specificLocation" width="130"
          label="具体位置" />
        <!-- <el-table-column key="equipmentType" show-overflow-tooltip prop="equipmentType" label="设备类型" /> -->
        <el-table-column align="center" key="responsiblePersonId" show-overflow-tooltip prop="responsiblePersonId"
          label="责任人编号" />
        <el-table-column align="center" key="responsiblePersonName" show-overflow-tooltip prop="responsiblePersonName"
          label="责任人姓名" />
        <el-table-column align="center" key="userId" show-overflow-tooltip prop="userId" label="使用人编号" />
        <el-table-column align="center" key="userName" show-overflow-tooltip prop="userName" label="使用人姓名" />
        <el-table-column align="center" key="locationCode" show-overflow-tooltip prop="locationCode" label="地点编码"
          width="150" />
        <el-table-column align="center" key="locationDescription" show-overflow-tooltip prop="locationDescription"
          label="地点描述" width="170" />
        <el-table-column align="center" key="manufacturer" show-overflow-tooltip prop="manufacturer" label="生产厂商" />
        <el-table-column align="center" key="specificationModel" show-overflow-tooltip prop="specificationModel"
          label="规格型号" />
        <el-table-column align="center" key="assetNote" show-overflow-tooltip prop="assetNote" label="资产名称备注"
          width="130" />

        <el-table-column align="center" show-overflow-tooltip label="状态" fixed="right">
          <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.status == 1">已盘查</el-tag>
            <el-tag type="danger" v-else>未盘查</el-tag>
          </template>

        </el-table-column>
        <el-table-column align="center" show-overflow-tooltip label="是否合格" fixed="right">
          <template slot-scope="scope" v-if="scope.row.checkResult != null">
            <el-tag type="success" v-if="scope.row.checkResult == 1">合格</el-tag>
            <el-tag type="danger" v-else>不合格</el-tag>
          </template>

        </el-table-column>
        <el-table-column   width="150" align="center" key="updateTimeCheck" show-overflow-tooltip prop="updateTimeCheck" label="盘查时间"
        fixed="right" />
        <!-- 表格操作列 -->
        <el-table-column align="center" label="操作" width="260"  fixed="right">
          <template slot-scope="scope">
            <el-button-group>
              <el-button style="margin-right: 10px;" size="mini" type="primary" :disabled="!scope.row.status" @click="handleDetail(scope.row)">
                盘查详情
              </el-button>
              <el-button size="mini"   type="danger" @click="handleDel(scope.row)">
                删除
              </el-button>
            </el-button-group>

          </template>
        </el-table-column>
      </el-table>
      <!-- 分页信息 -->
      <div class="pagination-container">
        <el-pagination background layout="total, prev, pager, next, jumper" @current-change="handlePageChange"
          @size-change="handleSizeChange" :current-page="pageNum" :total="tableData.total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog title="盘查详情" :visible.sync="showEditDialog" :before-close="handleDialogClose">
      <equipment-table-edit :mode="mode" ref="editForm" :record="currentRecord" @after-edit="handleAfterEdit" />
    </el-dialog>
    <el-dialog title="导入设备" :visible.sync="exportShow" @close="handleClose">
      <div style="display: flex;justify-content: center;">
        <el-upload ref="upload" class="upload-demo" :limit="1" accept=".xlsx" drag :action="action" multiple
          :headers="headers" :on-success="handleAvatarSuccess" :on-error="handleAvatarError"
          :before-upload="handleBefore">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        </el-upload>
      </div>
      <div style="width: 40%;margin: 0 auto;" v-if="errorMsg">
        <el-alert title="错误提示" type="error" :closable="false">
        </el-alert>
        <div style="margin: 10px 0;">{{ errorMsg }}</div>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import EquipmentTableApi from '../api/equipmentTable'
import equipmentTableEdit from './equipmentTableEdit'
import ImportExcel from '@/components/ImportExcel'
import DepartmentApi from "../../department/api/department.js"
import { getToken } from '@/utils/auth'
import { URL } from '@/api/api'
import { parseTime } from '@/utils'
import { Message, Loading } from 'element-ui'
export default {
  name: 'EquipmentTableList',
  components: {
    equipmentTableEdit,
    ImportExcel
  },
  data() {
    return {
      /* 搜索请求数据*/
      action: URL + "/equipmenttable/import",
      headers: {
        Authorization: getToken(),
      },
      loading: null,
      searchForm: {
        createdTime: new Date()
      },
      pageSize: 10,
      pageNum: 1,
      // 表格数据
      tableData: {
        results: []
      },
      mode: 'edit',
      // 是否显示添加/编辑对话框
      showEditDialog: false,
      // 当前处理行
      currentRecord: {},
      queryLoading: false,
      exportLoading: false,
      autoWidth: true,
      bookType: 'xlsx',
      departmentData: [],
      defaultProps: {
        children: 'children',
        label: 'name',
        key: "id"
      },
      exportShow: false,
      checkedkeys: "",
      departmentCode: "",
      errorMsg: ""
    }
  },
  mounted() {
    this.$nextTick(() => {


      this.getDepartment()
    })

  },
  methods: {
    handleExportOut() {

      EquipmentTableApi.equipmentExport({ month: parseTime(this.searchForm.createdTime, '{y}{m}'), departmentId: this.departmentCode }).then(res => {
        let target = this.departmentData.filter(item => {
          return item.departmentCode == this.departmentCode
        })

        const elink = document.createElement('a');
        elink.download = `${target[0].name}${parseTime(this.searchForm.createdTime, '{y}-{m}')}.xlsx`;
        elink.style.display = 'none';
        const blob = new Blob([res.data], { type: 'application/x-msdownload' });
        elink.href = window.URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        document.body.removeChild(elink);
      })

    },
    handleBefore() {

      this.loading = Loading.service({
        lock: true,
        text: '文件上传中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.8)'
      })
    },
    handleClose() {
      this.exportShow = false
      this.$refs.upload.clearFiles()
      this.errorMsg = ""
    },
    handleAvatarSuccess(resp) {
      if (resp.code === 200) {
        this.templateName = resp.data.fileName
        this.sheetList = resp.data.sheetNames
        this.errorData = []
        Message.success(resp.data)
        this.exportShow = false
        this.getDepartment()
      } else {
        this.templateName = ''
        this.sheetList = []
        this.errorData = resp.data
        // Message.error("模板上传失败，格式错误")
        this.$refs.upload.clearFiles()
        this.errorMsg = resp.message
      }
      this.loading.close()
    },
    handleAvatarError(error) {
      this.loading.close()
      Message.error("模板上传失败，格式错误!")
    },
    handleChange(id, departmentCode) {
      this.checkedkeys = id
      this.departmentCode = departmentCode
      this.init()
    },
    handleExport() {
      this.exportShow = true
    },
    getDepartment() {

      DepartmentApi
        .queryByCond({}, 1, 100)
        .then(response => {
          const data = response.data
          if (data.code === 200) {
            const list = response.data.data.list
            this.departmentData = list; // 构建树形结构

            if (this.$route.query.departmentCode) {
              let target = response.data.data.list.filter(item => item.departmentCode == this.$route.query.departmentCode)
              if (target && target.length > 0) {
                this.checkedkeys = target[0].id
              }
              this.departmentCode = this.$route.query.departmentCode
            } else {

              this.checkedkeys = this.departmentData[0].id
              this.departmentCode = this.departmentData[0].departmentCode
            }

            this.init()
          } else {
            Message.error(data.message)
            reject()
          }

        })
    },
    // 页面初始化
    init() {
      this.handleQuery()
    },
    handleQuery() {
      this.pageNum = 1
      this.query()
    },
    handleExportExcel() {
      this.exportLoading = true
      let param = {}
      param = Object.assign({}, this.searchForm)
      EquipmentTableApi
        .queryByCond(param, 0, 0).then(rspData => {
          let datalist = []
          datalist = rspData.data.data.list
          import('@/vendor/Export2Excel').then(excel => {
            const tHeader = [
              '资产标签号',
              '设备名字',
              '具体位置',
              '设备类型',
              '责任人编号',
              '责任人姓名',
              '使用人编号'
            ]
            const filterVal = [
              'assetTag',
              'name',
              'specificLocation',
              'equipmentType',
              'responsiblePersonId',
              'responsiblePersonName',
              'userId'
            ]
            const list = datalist
            const data = this.formatJson(filterVal, list)
            excel.export_json_to_excel({
              header: tHeader,
              data,
              filename: '导出Excel',
              autoWidth: this.autoWidth,
              bookType: this.bookType
            })
            this.exportLoading = false
          })
        }).catch(error => {
          this.exportLoading = false
          //console.log(error)
          if (error.message !== '') {
            //Message.error(error.message)
          }
        })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        return v[j]
      }))
    },
    query() {
      return new Promise((resolve, reject) => {
        this.queryLoading = true
        const param = Object.assign({}, this.searchForm)
        EquipmentTableApi
          .queryByCond({ createdTime: parseTime(this.searchForm.createdTime, '{y}-{m}-{d} {h}:{i}:{s}'), locationCode: this.departmentCode }, this.pageSize, this.pageNum)
          .then(response => {
            const data = response.data
            if (data.code === 200) {
              const data = response.data.data
              this.tableData = data
            } else {
              Message.error(data.message)
              reject()
            }
            this.queryLoading = false
          })
          .catch(error => {
            if (error.message !== '') {
              //Message.error(error.message)
            }
            this.queryLoading = false
            reject(error)
          })
      })
    },
    mockData() {
      setTimeout(() => {
        this.tableData = {
          total: 3, list: [
            {
              'assetTag': '资产标签号-Data-1',
              'name': '设备名字-Data-1',
              'specificLocation': '具体位置-Data-1',
              'equipmentType': '设备类型-Data-1',
              'responsiblePersonId': '责任人编号-Data-1',
              'responsiblePersonName': '责任人姓名-Data-1',
              'userId': '使用人编号-Data-1',
            },
            {
              'assetTag': '资产标签号-Data-2',
              'name': '设备名字-Data-2',
              'specificLocation': '具体位置-Data-2',
              'equipmentType': '设备类型-Data-2',
              'responsiblePersonId': '责任人编号-Data-2',
              'responsiblePersonName': '责任人姓名-Data-2',
              'userId': '使用人编号-Data-2',
            },
            {
              'assetTag': '资产标签号-Data-3',
              'name': '设备名字-Data-3',
              'specificLocation': '具体位置-Data-3',
              'equipmentType': '设备类型-Data-3',
              'responsiblePersonId': '责任人编号-Data-3',
              'responsiblePersonName': '责任人姓名-Data-3',
              'userId': '使用人编号-Data-3',
            },
          ]
        }
      }, 1000)
    },
    handleAdd() {
      this.mode = 'add'
      this.currentRecord = {}
      this.showEditDialog = true
    },
    handleDetail(row) {
      this.mode = 'details'
      this.currentRecord = Object.assign({}, row)
      this.showEditDialog = true
    },
    handleEdit(row) {
      this.mode = 'edit'
      this.currentRecord = Object.assign({}, row)
      this.showEditDialog = true
    },

    // 处理翻页事件
    handlePageChange(currentPage) {
      this.pageNum = currentPage
      this.query()
    },
    // 处理页面总条数事件
    handleSizeChange(val) {
      this.pageSize = val;
      this.query()
    },
    // 处理对话框关闭事件
    handleDialogClose(done) {
      this.showEditDialog = false
    },
    handleDel(row) {
      this.$confirm('确定删除吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const param = Object.assign({}, row)
          EquipmentTableApi.delete({ id: row.id })
            .then(response => {
              const data = response.data
              if (data.code === 200) {
                this.$message({
                  message: '删除成功',
                  type: 'success'
                })
                this.handleQuery()
              } else {
                Message.error(data.message)
              }
            })
            .catch(error => {
              //console.log(error)
              if (error.message !== '') {
                //Message.error(error.message)
              }
            })
        }).catch(() => {
        })
    },
    // 处理编辑对话框关闭事件
    handleAfterEdit() {
      this.showEditDialog = false
      this.$refs.editForm.resetFields()
      this.query()
    },
    buildTree(list) {
      const map = {};
      const roots = [];
      list.forEach((item) => {
        map[item.id] = { ...item, children: [] };
      });
      list.forEach((item) => {

        if (item.parentId && map[item.parentId]) {
          map[item.parentId].children.push(map[item.id]);
        } else if (item.parentId === null) {
          roots.push(map[item.id]); // parentId 为 null 的节点作为根节点
        } else {
          roots.push(map[item.id])
        }
      });
      console.log(roots, 888)
      return roots;
    },
    handleNodeClick() { },

  }
}
</script>
<style scoped>
.container {
  margin: 10px;
  display: flex;
  gap: 20px;
}

.table-container {
  margin-top: 0px;
}

.pagination-container {
  margin-top: 30px;
  text-align: right;
}

::v-deep .el-tree {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.showcChecked {
  background: #1890ff;
  color: #fff;

}
</style>
